import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:oktoast/oktoast.dart';
import 'package:rapid_kit/rapid_kit.dart';
import '../../sample/configure/constants.dart';
import '../../theme.dart';
import '../../utils/LogUtils.dart';
import '../../utils/lifecycle_aware.dart';
import '../../utils/snack_tips.dart';
import '../../widgets/global_widgets.dart';
import 'notification.dart';

/// 消息报警 - demo自带 - 未使用
class EventPage extends StatefulWidget {
  final String deviceId;

  const EventPage({super.key, required this.deviceId});

  @override
  State<EventPage> createState() => _EventPageState();
}

class _EventPageState extends LifecycleAwareState<EventPage> {
  static const double _thumbnailWidth = 120.0;
  static const double _thumbnailHeight = 68.0;
  final int _playTextureId = -1;
  bool _playing = false;
  static const int _pageSize = 30;
  late String _deviceId;
  int _selectedCategoryIndex = 0;
  int _selectedEventIndex = 0;
  bool _eventsLoading = true;
  final List<Event> _events = [];
  List<Category> _categories = [];
  DateTime _selectedDate = DateTime.now();
  final DateTime _todayDate = DateTime.now();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _buildTitleBar(context),
      body: _buildRootBody(context),
    );
  }

  AppBar _buildTitleBar(BuildContext context) {
    return AppBar(
      title: const Text('报警消息999', style: TextStyle(color: SampleThemeConfigure.colorPrimary)),
      backgroundColor: SampleThemeConfigure.colorBackground,
      leading: IconButton(
        icon: const Icon(Icons.arrow_back, color: SampleThemeConfigure.colorPrimary),
        onPressed: () {
          Navigator.pop(context);
        },
      ),
      actions: <Widget>[
        if (SampleConstants.fullAbilitiesMode)
          IconButton(
            icon: const Icon(Icons.settings),
            onPressed: () {
              Navigator.push(context, MaterialPageRoute(builder: (context) => NotificationPage(deviceId: _deviceId)));
            },
          ),
      ],
      elevation: 0,
    );
  }

  Widget _buildRootBody(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        double width = constraints.maxWidth;
        double height = width * 9 / 16;

        return Column(
          children: <Widget>[
            if (SampleConstants.fullAbilitiesMode)
              // 上面图片
              Container(
                width: width,
                height: height,
                color: const Color(0xFF252525),
                child: _playBody(),
              ),
            Expanded(
              child: _buildRootBottom(),
            ),
          ],
        );
      },
    );
  }

  Widget _playBody() {
    if (_events.isEmpty) {
      return Container();
    }

    if (_selectedEventIndex < 0 && _selectedEventIndex >= _events.length) {
      return Container();
    }

    final selectedEvent = _events[_selectedEventIndex];
    final containsVideo = selectedEvent.containsVideo ?? false;

    return Stack(
      children: [
        _topImageCover(selectedEvent),
        if (containsVideo)
          Texture(
            textureId: _playTextureId,
          ),
        if (containsVideo) _playControl(),
      ],
    );
  }

  Positioned _playControl() {
    return Positioned(
      right: 16.0,
      bottom: 16.0,
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(24.0),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.05),
              spreadRadius: 1,
              blurRadius: 8,
              offset: const Offset(3, 3),
            ),
          ],
        ),
        child: IconButton(
          icon: Icon(
            _playing ? Icons.pause_circle_filled : Icons.play_circle_filled,
            size: 40.0,
            color: Colors.white,
          ),
          onPressed: () {
            setState(() {
              _playing = !_playing;
            });
          },
        ),
      ),
    );
  }

  Image _topImageCover(Event selectedEvent) {
    return Image.network(
      selectedEvent.image ?? "",
      width: double.infinity,
      height: double.infinity,
      fit: BoxFit.cover,
    );
  }

  Widget _buildRootBottom() {
    return Column(
      children: <Widget>[
        // 筛选条件
        _categoriesBar(),
        _listContainer(),
      ],
    );
  }

  Widget _listContainer() {
    if (!_eventsLoading && _events.isEmpty) {
      return _emptyTips();
    }

    return Expanded(
      child: _eventsLoading
          ? createCenterLoading(size: 20.0)
          : RefreshIndicator(
              backgroundColor: SampleThemeConfigure.colorPrimary,
              color: Colors.white,
              displacement: 50,
              onRefresh: _pullToRefresh,
              child: _eventList(),
            ),
    );
  }

  // 没有数据显示
  Expanded _emptyTips() {
    return Expanded(
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: const [
            Icon(Icons.event_note, size: 50, color: SampleThemeConfigure.colorPrimary),
            SizedBox(height: 10),
            Text(
              '当日无事件',
              style: TextStyle(
                fontSize: 16,
                color: SampleThemeConfigure.colorPrimary,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _pullToRefresh() async {
    _events.clear();
    return _loadEventsOfDate();
  }

  Container _categoriesBar() {
    return Container(
      height: 60.0,
      padding: const EdgeInsets.symmetric(horizontal: 16.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          _datePicker(),
          _eventCategory(),
        ],
      ),
    );
  }

  Widget _eventCategory() {
    return GestureDetector(
      onTap: () async => _onPickCategory(),
      child: Container(
        padding: const EdgeInsets.all(8.0),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12.0),
        ),
        child: const Icon(
          Icons.filter_list,
          size: 22,
          color: SampleThemeConfigure.colorTextPrimary,
        ),
      ),
    );
  }

  GestureDetector _datePicker() {
    return GestureDetector(
      onTap: () async => _onPickDate(),
      child: Row(
        children: <Widget>[
          Text(
            _formattedDateString(),
            style: const TextStyle(fontSize: 16.0, color: SampleThemeConfigure.colorTextPrimary),
          ),
          const Padding(
            padding: EdgeInsets.only(left: 0),
            child: Icon(
              Icons.arrow_drop_down_rounded,
              size: 30,
              color: SampleThemeConfigure.colorTextPrimary,
            ),
          )
        ],
      ),
    );
  }

  String _formattedDateString() {
    String formattedDate = _selectedDate.toChineseDate();

    if (_todayDate.day == _selectedDate.day) {
      formattedDate = "$formattedDate | 今天";
    }
    return formattedDate;
  }

  ListView _eventList() {
    return ListView.builder(
      itemCount: _events.length + 1,
      itemBuilder: (context, index) {
        if (index == _events.length) {
          return _loadMore();
        } else {
          return _eventCard(index);
        }
      },
    );
  }

  // 没有数据
  Padding _loadMore() {
    return Padding(
      padding: const EdgeInsets.only(left: 16, right: 16, bottom: 16),
      child: GestureDetector(
        onTap: () => _loadEventsOfDate(),
        child: Container(
          decoration: BoxDecoration(
            color: SampleThemeConfigure.colorTextHint,
            borderRadius: BorderRadius.circular(8.0),
          ),
          padding: const EdgeInsets.symmetric(vertical: 10.0, horizontal: 24.0),
          child: const Center(
            child: Text(
              '点击加载更多',
              style: TextStyle(
                color: Colors.white,
                fontSize: 14.0,
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _eventCard(int index) {
    return GestureDetector(
      onTap: () {
        setState(() {
          _selectedEventIndex = index;
        });
      },
      child: _buildEventCard(index),
    );
  }

  // 每一条数据
  Widget _buildEventCard(int index) {
    final event = _events[index];
    final selected = index == _selectedEventIndex;
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.0),
      ),
      margin: const EdgeInsets.only(left: 16, right: 16, bottom: 16),
      child: Padding(
        padding: const EdgeInsets.only(left: 16, right: 5, bottom: 5, top: 5),
        child: Row(
          children: <Widget>[
            _cardIcon(event),
            const SizedBox(width: 20.0),
            _cardDesc(event, selected),
            const SizedBox(width: 12.0),
            Padding(
              padding: const EdgeInsets.all(8),
              child: _cardThumbnail(selected, event),
            ),
          ],
        ),
      ),
    );
  }

  // 头部
  Container _cardIcon(Event event) {
    return Container(
      width: 40,
      height: 40,
      decoration: const BoxDecoration(
        color: Color.fromARGB(255, 255, 170, 59),
        shape: BoxShape.circle,
      ),
      child: Padding(
        padding: const EdgeInsets.all(10.0),
        child: ClipOval(
          child: Image.network(
            event.detail?.categoryIcon ?? "",
            fit: BoxFit.cover,
            color: Colors.white,
            colorBlendMode: BlendMode.srcATop,
          ),
        ),
      ),
    );
  }

  // 中间数据 - 发现移动 - 时间
  Expanded _cardDesc(Event event, bool selected) {
    return Expanded(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            event.detail?.categoryName ?? "",
            style: TextStyle(
              fontSize: 16.0,
              fontWeight: FontWeight.bold,
              color: selected && SampleConstants.fullAbilitiesMode ? SampleThemeConfigure.colorPrimary : SampleThemeConfigure.colorTextPrimary,
            ),
          ),
          Text(
            (event.startTime ?? 0).toHHmmss(),
            style: TextStyle(
              fontSize: 14.0,
              color: selected && SampleConstants.fullAbilitiesMode ? SampleThemeConfigure.colorPrimary : Colors.grey,
            ),
          ),
        ],
      ),
    );
  }

  // 图片
  ClipRRect _cardThumbnail(bool selected, Event event) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(12.0),
      child: Stack(
        children: [
          Image.network(
            event.thumbnail ?? "",
            width: _thumbnailWidth,
            height: _thumbnailHeight,
            fit: BoxFit.cover,
          ),
          if (SampleConstants.fullAbilitiesMode && selected) _cardThumbnailSelectedCover(),
        ],
      ),
    );
  }

  // 图片提示
  Container _cardThumbnailSelectedCover() {
    return Container(
      width: _thumbnailWidth,
      height: _thumbnailHeight,
      color: Colors.black.withOpacity(0.5),
      child: const Center(
        child: Text(
          "播放中",
          style: TextStyle(
            color: Colors.white,
            fontSize: 14.0,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
    );
  }

  void _onPickDate() async {
    DateTime? pickedDate = await showDatePicker(
      context: context,
      initialDate: _selectedDate,
      firstDate: DateTime(2000),
      lastDate: DateTime(2101),
    );

    if (pickedDate != null && pickedDate != _selectedDate) {
      setState(() {
        _selectedDate = pickedDate;
        _eventsLoading = true;
      });

      _loadEventsOfDate();
    }
  }

  @override
  void initState() {
    super.initState();
    _deviceId = widget.deviceId;
    _loadCategories();
    _loadEventsOfDate();
  }

  void _loadEventsOfDate() async {
    List<String> categoriesLabel = [];
    if (_selectedCategoryIndex > 0 && _categories.isNotEmpty) {
      final category = _categories[_selectedCategoryIndex - 1];
      categoriesLabel.add(category.categoryLabel ?? "");
    }
    LogUtils.e(_deviceId);
    LogUtils.e(_events.length);
    LogUtils.e(categoriesLabel);
    final eventsResp = await EventService.eventsByPage(_deviceId, _selectedDate.toStandardDate(), _events.length,
        catagoriesLabel: categoriesLabel, limit: _pageSize);
    if (mounted) {
      if (eventsResp.success) {
        LogUtils.w(eventsResp.data);
        final size = eventsResp.data?.length ?? 0;

        if (size < 1 && _events.isNotEmpty) {
          SnackTips.show(context, "没有更多数据了");
          return;
        }

        if (size > 0) {
          _events.addAll(eventsResp.data!);
        }

        setState(() {
          _eventsLoading = false;
        });
      } else {
        SnackTips.show(context, "message: ${eventsResp.message}");
      }
    }
  }

  // 查询筛选类型
  void _loadCategories() async {
    final categoriesResp = await EventService.catagories(_deviceId);
    if (mounted) {
      if (categoriesResp.success) {
        setState(() {
          _categories = categoriesResp.data!.list ?? [];
          LogUtils.w(categoriesResp.data!.list);
        });
      } else {
        SnackTips.show(context, "message: ${categoriesResp.message}");
      }
    }
  }

  // 筛选
  void _onPickCategory() {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return ListView.separated(
          itemCount: _categories.length + 1,
          itemBuilder: (BuildContext context, int index) {
            String categoryName;

            if (index == 0) {
              categoryName = '全部';
            } else {
              final category = _categories[index - 1];
              categoryName = category.categoryName ?? 'No Label';
            }

            return ListTile(
              leading: Icon(
                _selectedCategoryIndex == index ? Icons.check_circle : Icons.circle_outlined,
                color: _selectedCategoryIndex == index ? SampleThemeConfigure.colorPrimary : Colors.grey,
              ),
              title: Text("${categoryName}===测试122"),
              onTap: () {
                showToast("${categoryName}===测试");
                if (_selectedCategoryIndex != index) {
                  _selectedCategoryIndex = index;
                  _events.clear();
                  setState(() {
                    _eventsLoading = true;
                  });
                  _loadEventsOfDate();
                }
                Navigator.pop(context);
              },
            );
          },
          separatorBuilder: (BuildContext context, int index) => const Divider(),
        );
      },
    );
  }
}
